package pers.cz.spring;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * sprign工具类，用于返回bean对象
 * @program: PostGirl-panent
 * @description: SpringContextUtil
 * @author: Cheng Zhi
 * @create: 2021-03-13 17:08
 **/
@Component
public class SpringContextUtil implements ApplicationContextAware {

    public static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }
    public static <T> T getBean(Class<T> t) {
        return applicationContext.getBean(t);
    }

    public Object getSpringBean(String s) {
        return  applicationContext.getBean(s);
    }

    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }

    public static String[] getBeanNames() {
        String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
        return beanDefinitionNames;
    }

    public static Object getBeanByReflection(String className) throws BeansException, ClassNotFoundException {
        return applicationContext.getBean(Class.forName(className));
    }
}
